package diaodu.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import diaodu.adapter.DispatchAdapter;
import diaodu.dto.WaterDispatch;
import gongqing.views.adapters.DevTypeChooseAdapter;
import inter.DownloadInfo;
import managers.UIHandler;
import managers.VolleySingleton;

/**
 * 调度查看
 * Created by Administrator on 2017/6/3.
 */

public class DiaoDuShowActivity extends UIHandler.BaseActivity {

    // 返回
    Button btn_back;

    // 基本设备
    ListView lv_info;

    // 选择
    Spinner sp_devType;

    PullToRefreshListView pullToRefreshListView;

    int type = 1;



    diaodu.adapter.DispatchAdapter dispatchAdapter;

    List<WaterDispatch> dispatchList = new ArrayList<>();

    long upperTime = Calendar.getInstance().getTimeInMillis();

    View.OnClickListener itemClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_back) {
                finish();
            }
        }
    };


    // 移除position项并刷新
    public void removeAndNotify(int position) {
        dispatchList.remove(position);
        dispatchAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diaodu);

        // 返回
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(itemClick);

        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.id_refreshlistview);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getmore();
            }
        });


        // 信息列表
        lv_info = pullToRefreshListView.getRefreshableView();

        sp_devType = (Spinner) findViewById(R.id.id_sp_type);

        DevTypeChooseAdapter devTypeChooseAdapter = new DevTypeChooseAdapter();
        devTypeChooseAdapter.setDevtype(MyApplication.share().getResources().getStringArray(R.array.dispatchType));
        sp_devType.setAdapter(devTypeChooseAdapter);
        sp_devType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type = position + 1;
                initByType(type);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        // 设置设备数据源
        dispatchAdapter = new DispatchAdapter();
        dispatchAdapter.setDispatchList(dispatchList);
        lv_info.setAdapter(dispatchAdapter);
//        lv_info.setDividerHeight((int) getResources().getDimension(R.dimen.y8));

        lv_info.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                WaterDispatch dispatch = dispatchList.get(i-1);
                Intent intent = new Intent(DiaoDuShowActivity.this,DealDispatchActivity.class);
                intent.putExtra("dispatch",dispatch);
                intent.putExtra("position",i-1);
                DiaoDuShowActivity.this.startActivity(intent);
            }
        });

        TextView emptyView = (TextView) findViewById(R.id.emptyView);
        emptyView.setTypeface(MyApplication.iconfont);
        lv_info.setEmptyView(emptyView);
    }

    private void initByType(final int type) {

        showDialog();
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/guanqu/GetWaterDispatch";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        closeDialog();
                        if (!response.startsWith("{"))
                        {
                            return;
                        }

                        Download download = new Gson().fromJson(response,Download.class);
                        if (download.getStatus() == DownloadInfo.FAILED)
                        {
                            Toast.makeText(MyApplication.share(),"数据获取失败",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (download.dispatchs.isEmpty())
                        {
                            Toast.makeText(MyApplication.share(),"没有未处理请求",Toast.LENGTH_SHORT).show();
                        }
                        dispatchList.clear();
                        dispatchList.addAll(download.dispatchs);
                        dispatchAdapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                closeDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("type", type+"");
                map.put("time", Calendar.getInstance().getTimeInMillis()+"");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }

    private void getmore() {

        showDialog();
        upperTime = dispatchList.get(dispatchList.size()-1).getSendTime().getTimeInMillis();

        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/guanqu/GetWaterDispatch";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        closeDialog();
                        if (!response.startsWith("{"))
                        {
                            return;
                        }

                        Download download = new Gson().fromJson(response,Download.class);
                        if (download.getStatus() == DownloadInfo.FAILED)
                        {
                            Toast.makeText(MyApplication.share(),"数据获取失败",Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (download.dispatchs.isEmpty())
                        {
                            Toast.makeText(MyApplication.share(),"没有更多了",Toast.LENGTH_SHORT).show();
                            pullToRefreshListView.onRefreshComplete();
                            return;
                        }
                        dispatchList.addAll(download.dispatchs);
                        dispatchAdapter.notifyDataSetChanged();
                        pullToRefreshListView.onRefreshComplete();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                pullToRefreshListView.onRefreshComplete();
                closeDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("type", type+"");
                map.put("time", upperTime+"");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }


    static class Download {
        int status;

        List<WaterDispatch> dispatchs = new ArrayList<>();

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<WaterDispatch> getDispatchs() {
            return dispatchs;
        }

        public void setDispatchs(List<WaterDispatch> dispatchs) {
            this.dispatchs = dispatchs;
        }
    }
}
